package me.ahoukuse.koala.interceptor;

import com.alibaba.fastjson2.JSONObject;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import me.ahoukuse.koala.util.JwtUtil;
import me.ahoukuse.koala.util.MessageUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class UserValidateInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        String authorization = request.getHeader("Authorization");
        log.info("Authorization = {}", authorization);
        if (authorization == null || authorization.isEmpty()) {
            JSONObject res = MessageUtil.msg(401, "未登录");
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(res.toString());
            return false;
        }
        String[] auths = authorization.trim().split(" ");
        if (auths.length < 2) {
            log.info("JWT IS NOT VALIDATED");
            JSONObject res = MessageUtil.msg(401, "未登录");
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(res);
            return false;
        }
        String authType = auths[0].trim();
        String token = auths[1].trim();
        Claims claims = JwtUtil.parseClaims(token);
        if (claims == null) {
            log.info("JWT IS NOT VALIDATED");
            JSONObject res = MessageUtil.msg(401, "未登录");
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(res.toString());
            return false;
        }
        log.info("userId = {}", claims.get("userId"));
        return true;
    }
}
